package com.zzyl.common.utils.deepseek;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.List;

@Data
@AllArgsConstructor
public class ChatClient {
    private String baseUrl;
    private String apiKey;
    private String model;
    private String defaultSystem;


    public String chat(String prompt) {
        try {
            // 检查必要参数
            if (baseUrl == null || baseUrl.isEmpty()) {
                System.err.println("Base URL is null or empty");
                return null;
            }
            if (apiKey == null || apiKey.isEmpty()) {
                System.err.println("API Key is null or empty");
                return null;
            }
            if (model == null || model.isEmpty()) {
                System.err.println("Model is null or empty");
                return null;
            }

            // 清理API密钥，去除可能的空格或特殊字符
            String cleanApiKey = apiKey.trim();
            
            // 1.创建请求体对象
            ChatRequest request = ChatRequest.builder()
                    .model(model)
                    .messages(List.of(
                            Message.userMessage(prompt)
                    ))
                    .stream(false)
                    .build();

            System.out.println("Sending request to: " + baseUrl);
            System.out.println("Request body: " + JSONUtil.toJsonStr(request));

            // 2.调用DeepSeek
            HttpResponse response = HttpRequest.post(baseUrl)
                    .header("Authorization", "Bearer " + cleanApiKey)
                    .body(JSONUtil.toJsonStr(request))
                    .execute();
            
            //3.解析结果
            System.out.println("Response status: " + response.getStatus());
            if (response.isOk()) {
                // 1.获取响应体
                String body = response.body();
                System.out.println("Response body: " + body);
                
                // 2.将响应体转为JSON对象
                JSONObject jsonObject = JSONUtil.parseObj(body);
                // 3.获取内容
                String content = jsonObject.getByPath("choices[0].message.content", String.class);
                return content;
            } else {
                System.err.println("Request failed with status: " + response.getStatus());
                String errorBody = response.body();
                System.err.println("Error body: " + errorBody);
                return null;
            }
        } catch (Exception e) {
            System.err.println("Error occurred while sending chat request: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
}